package DAOs;

// Generated 06-ago-2012 23:22:36 by Hibernate Tools 4.0.0

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import POJOs.ClientePOJO;
import POJOs.OfertaPOJO;

public class OfertaDAO {	

	private static SessionFactory sessionFactory;	
	private Session session;
	
	public OfertaDAO() {
		
		try {
						
			Configuration configuration = new Configuration();
			configuration.configure("hibernate.cfg.xml");			
			sessionFactory = configuration.buildSessionFactory();
			session = sessionFactory.openSession();
                        
		} catch (Throwable ex) {
			System.err.println("Failed to create sessionFactory object." + ex);
			throw new ExceptionInInitializerError(ex);
		} 
		
	}	

	public void delete(OfertaPOJO persistentInstance) {
		try {
			session.delete(persistentInstance);
		} catch (RuntimeException re) {
			throw re;
		}
	}
	
	public void save(OfertaPOJO instance) {		
		Transaction tx = null;
		try {						
			tx = session.beginTransaction();
			session.saveOrUpdate(instance);			
			tx.commit();			
		}catch (Exception re){
			tx.rollback();
		}
	}
	
	public List<OfertaPOJO> findAll(){				
		Transaction tx = null;		
		try{		
			tx = session.beginTransaction();
			Query query = this.session.createQuery("from OfertaPOJO");
			List<OfertaPOJO> listaResult = query.list();
			tx.commit();
			return listaResult;
		}catch(Exception re){
			return null;
		}		
	}
	
	public List<OfertaPOJO> cargarOfertas(Integer clienteId) {
		Query query = session.createQuery("from OfertaPOJO where id_usuario = :id_usuario");		
		query.setParameter("id_usuario", clienteId);
		List<OfertaPOJO> listaOfertas = query.list();
		return listaOfertas;	
	}

	public OfertaPOJO findById(java.lang.Integer id) {
		try {
			OfertaPOJO instance = (OfertaPOJO) session.get("com.bbdd_gtweb.model.ofertas", id);
			if (instance == null) {
			} else {
			}
			return instance;
		} catch (RuntimeException re) {
			throw re;
		}
	}

}
